<!--
 * @Description: 
 * @Version: 1.0
 * @Author: zhanzghen
 * @Date: 2025-08-07 19:44:06
 * @LastEditors: zhanzghen
 * @LastEditTime: 2025-08-07 20:48:10
-->
<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <template v-if="userInfo.imgPath">
        <img :src="userInfo.imgPath" alt="avatar" />
      </template>
      <template v-else>
        <img src="@/assets/images/avatar.png" alt="avatar" />
      </template>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="openDrawer">
          <el-icon><User /></el-icon>{{ $t("header.personalData") }}
        </el-dropdown-item>
        <el-dropdown-item @click="openThemeDrawer">
          <el-icon><Setting /></el-icon>主题风格
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <el-icon><SwitchButton /></el-icon>{{ $t("header.logout") }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <info-drawer ref="infoDrawerRef"></info-drawer>
  <ThemeDrawer v-model="themeDrawerVisible"></ThemeDrawer>
</template>

<script setup lang="ts">
import { ref, computed } from "vue"
import { LOGIN_URL } from "@/config"
import { useRouter } from "vue-router"
import { logoutApi } from "@/api/modules/login"
import { useUserStore } from "@/stores/modules/user"
import { ElMessageBox, ElMessage } from "element-plus"
import InfoDrawer from "./InfoDrawer.vue"
import ThemeDrawer from "@/layouts/components/ThemeDrawer/index.vue"

const themeDrawerVisible = ref(false)
const infoDrawerRef = ref<InstanceType<typeof InfoDrawer>>()

const router = useRouter()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

/** 打开抽屉 */
const openDrawer = () => {
  infoDrawerRef.value?.handleOpen()
}
// 监听 mitt 事件
const openThemeDrawer = () => {
  themeDrawerVisible.value = true
}
/** 退出登录 */
const logout = () => {
  ElMessageBox.confirm("确定退出登录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    // 1.执行退出登录接口
    await logoutApi()
    ElMessage.success("退出登录成功！")
    // 2.清除 Token
    userStore.setToken("")
    // 3.清除本地数据
    window.localStorage.clear()
    // 4.重定向到登陆页
    router.replace(LOGIN_URL)
  })
}
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  margin-left: 20px;
  overflow: hidden;
  font-size: 15px;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
